package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.common.HTMLRe;
import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.IAction;
import com.liuqianfei.util.RegExpUtil;
import com.liuqianfei.util.StringUtil;

/**
 * Process html tags
 * @author liuqianfei
 */
public class HtmlInlineAction implements IAction
{
    private boolean isLetter(char ch)
    {
        /*eslint no-bitwise:0*/
        int lc = ch | 0x20; // to lower case
        return (lc >= 0x61/* a */) && (lc <= 0x7a/* z */);
    }

    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        char ch;
        Token token;
        String match;
        int max, pos = state.getPos();

        if (!state.getMd().configuration.html)
            return false;

        // Check start
        max = state.getPosMax();
        if (state.getSrc().charAt(pos) != 0x3C/* < */ || pos + 2 >= max)
            return false;

        // Quick fail on second char
        ch = state.getSrc().charAt(pos + 1);
        if (ch != 0x21/* ! */
                && ch != 0x3F/* ? */
                && ch != 0x2F/* / */
                && !isLetter(ch))
            return false;

        match = RegExpUtil.group(HTMLRe.HTML_TAG_RE, StringUtil.slice(state.getSrc(), pos), false, 0);
        if (StringUtil.isEmpty(match))
            return false;

        if (!silent)
        {
            token         = state.push("html_inline", "", 0);
            token.content = StringUtil.slice(state.getSrc(), pos, pos + match.length());
        }
        state.setPos(state.getPos() + match.length());
        return true;
    }
}
